package com.basketball.gym.utils;

import org.apache.http.HttpStatus;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.DefaultHttpRequestRetryHandler;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;

import java.io.IOException;
import java.util.Iterator;
import java.util.Map;

@Configuration
public class HttpService {
    @Autowired
    private Logger logger;
    @Autowired
    private PoolingHttpClientConnectionManager poolConnManager;
    @Autowired
    private RequestConfig requestConfig;

    public CloseableHttpClient getConnection() {
        RequestConfig config = RequestConfig.custom().setConnectTimeout(5000).setConnectionRequestTimeout(5000).setSocketTimeout(5000).build();
        return HttpClients.custom()
                // 设置连接池管理
                .setConnectionManager(poolConnManager)
                .setDefaultRequestConfig(config)
                // 设置重试次数
                .setRetryHandler(new DefaultHttpRequestRetryHandler(2, false)).build();
    }

    /**
     * 发起Get请求（无参）
     *
     * @param url：请求地址
     * @return map
     */
    public String httpGet(String url) {
        CloseableHttpClient httpClient = getConnection();
        HttpGet httpGet = new HttpGet(url);
        CloseableHttpResponse response = null;
        try {
            response = httpClient.execute(httpGet);
            String result = EntityUtils.toString(response.getEntity(), "utf-8");
            int code = response.getStatusLine().getStatusCode();
            if (code == HttpStatus.SC_OK) {
                return result;
            } else {
                logger.error("请求{}返回错误码：{},{}", url, code, result);
                return null;
            }
        } catch (IOException e) {
            logger.error("http请求异常，{}", url, e);
        } finally {
            try {
                if (response != null)
                    response.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return null;
    }


    /**
     * 有参GET请求
     *
     * @param url：请求地址
     * @param param：参数
     * @return map
     */
    public String httpGet(String url, Map<String, Object> param) {
        CloseableHttpClient httpClient = getConnection();
        Iterator<Map.Entry<String, Object>> it = param.entrySet().iterator();
        int i = 0;
        StringBuilder urlBuilder = new StringBuilder(url);
        while (it.hasNext()) {
            Map.Entry<String, Object> entry = it.next();
            if (i == 0) {
                urlBuilder.append("?").append(entry.getKey()).append("=").append(entry.getValue());
            } else {
                urlBuilder.append("&").append(entry.getKey()).append("=").append(entry.getValue());
            }
            i++;
        }
        url = urlBuilder.toString();
        System.out.println(url);
        HttpGet httpGet = new HttpGet(url);
        CloseableHttpResponse response = null;
        try {
            response = httpClient.execute(httpGet);
            String result = EntityUtils.toString(response.getEntity(), "utf-8");
            int code = response.getStatusLine().getStatusCode();
            if (code == HttpStatus.SC_OK) {
                return result;
            } else {
                logger.error("请求{}返回错误码：{},{}", url, code, result);
                return null;
            }
        } catch (IOException e) {
            logger.error("http请求异常，{}", url, e);
        } finally {
            try {
                if (response != null)
                    response.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return null;
    }
//    public static String post(String uri, Object params, Header... heads) {
//        HttpPost httpPost = new HttpPost(uri);
//        CloseableHttpResponse response = null;
//        try {
//            StringEntity paramEntity = new StringEntity(JSON.toJSONString(params));
//            paramEntity.setContentEncoding("UTF-8");
//            paramEntity.setContentType("application/json");
//            httpPost.setEntity(paramEntity);
//            if (heads != null) {
//                httpPost.setHeaders(heads);
//            }
//            response = httpClient.execute(httpPost);
//            int code = response.getStatusLine().getStatusCode();
//            String result = EntityUtils.toString(response.getEntity());
//            if (code == HttpStatus.SC_OK) {
//                return result;
//            } else {
//                logger.error("请求{}返回错误码:{},请求参数:{},{}", uri, code, params,result);
//                return null;
//            }
//        } catch (IOException e) {
//            logger.error("收集服务配置http请求异常", e);
//        } finally {
//            try {
//                if(response != null) {
//                    response.close();
//                }
//            } catch (IOException e) {
//                e.printStackTrace();
//            }
//        }
//        return null;
//    }
}
